//
//  RecordListController.swift
//  JianTingSwift
//
//  Created by zhibao on 2024/6/18.
//

class JianTingListController: SecSuperController,UITableViewDelegate,UITableViewDataSource,DataChangeDelegate,UIDocumentInteractionControllerDelegate,UIDocumentPickerDelegate {
    fileprivate var dataArray = [[String:Any]]()
    let loginBtn = UIButton(type: .custom)
    
    fileprivate var showTableView = MYTableView(frame: CGRectMake(0, navigationFullHeight(), SCREEN_WIDTH, SCREEN_HEIGHT - navigationFullHeight() - tabBarFullHeight()), style: .plain)
    fileprivate var document:UIDocumentInteractionController?
    fileprivate var mp3filePath  = ""
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if  UserInfoManager.shared().isLogin == true {
            loginBtn.isHidden = true
            self.showTableView.noDataType = .TableViewNoDataType_FILE
            self.getData()
        }else{
            loginBtn.isHidden = false
            self.showTableView.noDataType = .TableViewNoDataType_NOLOGINFILE
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = "历史录音"
        self.initTableview()
    }
    
    fileprivate func getData(){
        HttpHelper.sharedInstance().sendGet("api/record/list", parameters: [:]) { operation, responseObject in
            if responseObject.code == 1 {
                self.dataArray.removeAll()
                let tempData = responseObject.data as! [String:Any]
                let data = tempData["data"] as! [[String:Any]]
                for dic in data {
                    let tempDic = dic
                    self.dataArray.append(tempDic)
                }
                self.showTableView.reloadData()
            }
        } failure: { operation, error in
            
        }

    }
    
    fileprivate func initTableview(){
        showTableView.delegate = self
        showTableView.dataSource = self
        showTableView.dataChangeDelegate = self
        showTableView.separatorStyle = .none
        showTableView.register(JianTingCell.self, forCellReuseIdentifier: "JianTingCell")
        self.view.addSubview(showTableView)
        showTableView.noDataType = .TableViewNoDataType_FILE
        showTableView.mj_footer?.endRefreshingWithNoMoreData()
        
        loginBtn.frame = CGRect(x: 0, y: self.showTableView.nodataView.tipLabel.bottom + pixh(p: 30), width: pixw(p: 220), height: pixh(p: 50))
        loginBtn.backgroundColor = MYRed
        loginBtn.layer.cornerRadius = 22
        loginBtn.clipsToBounds = true
        loginBtn.setTitleColor(.white, for: .normal)
        loginBtn.titleLabel?.font = MY_SCALE_SemiboldFONT(14)
        loginBtn.addTarget(self, action: #selector(login), for: .touchUpInside)
        self.showTableView.addSubview(loginBtn)
        loginBtn.snp.makeConstraints { make in
            make.centerY.equalTo(self.showTableView).offset(100)
            make.centerX.equalTo(self.showTableView)
            make.height.equalTo(44)
            make.width.equalTo(120)
        }
        loginBtn.setTitle("登录", for: .normal)
    }
    
    @objc func login(){
        if  UserInfoManager.shared().isLogin == false {
            YJLoginHelper.login(with: self)
        }
    }
}
extension JianTingListController {
    func refreshData(withTabelViewTag tableViewTag: Int) {
        self.getData()
    }
    
    func loadMoreData(withTabelViewTag tableViewTag: Int) {
        self.getData()
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dic = dataArray[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "JianTingCell") as! JianTingCell
        cell.doneBlock = {
            if  UserInfoManager.shared().isLogin == false {
                YJLoginHelper.login(with: self)
                return
            }
            
            if UserInfoManager.shared().isVip() == false {
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            //分享
            let url = dic["url"] as! String
            Helper.newLoadData(url, withName: dic["title"] as? String) { mp3Url in
                self.shareFile(path: mp3Url ?? "")
            }
        }
        cell.updata(dic: dic,selectType: "0")
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if  UserInfoManager.shared().isLogin == false {
            YJLoginHelper.login(with: self)
            return
        }
        
        if UserInfoManager.shared().isVip() == false {
            Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                //去往购买中心
                if index == 1 {
                    let controller = PayMarkController()
                    self.navigationController?.pushViewController(controller, animated: true)
                }
            }
            return
        }
        
        let dic = dataArray[indexPath.row]
        let controller = CommPlayerController()
        controller.na_title = dic["text"] as! String
        controller.url = dic["audio_url"] as! String
        controller.type = .urlMp3
        self.navigationController?.pushViewController(controller, animated: true)
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let dataDic = dataArray[indexPath.row]
        let reNameAction = UIContextualAction(style: .normal, title: LocalizedString("重命名")) { (action, view, completed)  -> Void in
            if  UserInfoManager.shared().isLogin == false {
                YJLoginHelper.login(with: self)
                return
            }
            let flag = UserInfoManager.shared().isVip()
            if(flag == false){
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            Helper.alertShow(withTitle: LocalizedString("重命名"), withSureBtnTitle: LocalizedString("确定"), withCancelBtnTitle: LocalizedString("取消")) { anwer in
                if anwer!.qmui_trimAllWhiteSpace.count > 0 {
                    let url = "api/record/modify"
                    HttpHelper.sharedInstance().sendPut(url, parameters: ["id":dataDic["id"]!,"newTitle":anwer!.qmui_trimAllWhiteSpace]) { task, model in
                        if model.code == 1 {
                            QMUITips.showSucceed("修改成功")
                            self.getData()
                        }
                    } failure: { task, error in
                        
                    }
                }
            }
        }
        reNameAction.backgroundColor = MYColor.color(withHexString: "#1AB8A6")
        
        let deleteAction = UIContextualAction(style: .normal, title: LocalizedString("删除")) { (action, view, completed)  -> Void in
            if  UserInfoManager.shared().isLogin == false {
                YJLoginHelper.login(with: self)
                return
            }
            let flag = UserInfoManager.shared().isVip()
            if(flag == false){
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            Helper.alertShow(withTitle: LocalizedString("是否删除？"), withContent: "", withSureBtnTitle: LocalizedString("确定"), withCancelBtnTitle: LocalizedString("取消")) { selectIndex in
                if(selectIndex == 1){
                    let url = "api/record/remove"
                    HttpHelper.sharedInstance().sendPut(url, parameters: ["id":dataDic["id"]!]) { task, model in
                        if model.code == 1 {
                            QMUITips.showSucceed("删除成功")
                            self.getData()
                        }
                    } failure: { task, error in
                        
                    }
                }
            }
        }
        deleteAction.backgroundColor = MYColor.color(withHexString: "#FC2F55")
        
        let shareAction = UIContextualAction(style: .normal, title: LocalizedString("分享")) { [self] (action, view, completed)  -> Void in
            if  UserInfoManager.shared().isLogin == false {
                YJLoginHelper.login(with: self)
                return
            }
            let flag = UserInfoManager.shared().isVip()
            if(flag == false){
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            //分享
            let url = dataDic["url"] as! String
            Helper.newLoadData(url, withName: dataDic["title"] as? String) { mp3Url in
                self.shareFile(path: mp3Url ?? "")
            }
        }
        shareAction.backgroundColor = MYBlue
        
        let config = UISwipeActionsConfiguration(actions: [shareAction,deleteAction,reNameAction])
        config.performsFirstActionWithFullSwipe = false
        return config
    }
    
    fileprivate func shareFile(path:String){
        self.showTableView.reloadData()
        document = UIDocumentInteractionController(url:URL(string: path) ?? URL(fileURLWithPath: ""))
        document?.delegate = self
        let _ = self.document?.presentOptionsMenu(from: self.view.bounds, in: self.view, animated: true)
    }
}

extension JianTingListController{
    
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
    
    func documentInteractionControllerViewForPreview(_ controller: UIDocumentInteractionController) -> UIView? {
        return self.view
    }
    
    func documentInteractionControllerRectForPreview(_ controller: UIDocumentInteractionController) -> CGRect {
        return self.view.frame
    }
    
    func documentInteractionControllerDidDismissOpenInMenu(_ controller: UIDocumentInteractionController) {
        DLog(message: "disMiss")
    }
}

